package com.itcm.skymail.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcm.common.utils.PageUtils;
import com.itcm.common.utils.Query;
import com.itcm.skymail.product.dao.BrandDao;
import com.itcm.skymail.product.entity.BrandEntity;
import com.itcm.skymail.product.service.BrandService;
import com.itcm.skymail.product.service.CategoryBrandRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service("brandService")
@Slf4j
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        log.info("获取查询关键字：{}", key);

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>().like(StringUtils.isNotBlank(key), "name", key)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateAll(BrandEntity brand) {
        // 先更新brand表
        this.updateById(brand);

        if (!StringUtils.isEmpty(brand.getName())) {
            // 当品牌名变更时 冗余了品牌名的表就得同步更新
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
            // TODO 其他冗余品牌名的表 更新
        }
    }
}